package com.mobilesales.android.services;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.mobilesales.android.model.employees.EmployeeAccess;
import com.mobilesales.android.model.exceptions.ServiceUnavailableException;
import com.mobilesales.android.model.wrappedrequests.ChangePasswordRequest;
import com.mobilesales.android.model.wrappedrequests.LoginRequest;

public class AuthServiceClient extends ServiceClientBase {

	public AuthServiceClient(Configuration configuration) {
		super(configuration);
		// TODO Auto-generated constructor stub
	}

	public EmployeeAccess Login(String userName, String passwd, String c2dmRegistrationId) throws NoSuchAlgorithmException, UnsupportedEncodingException, ServiceUnavailableException{
		EmployeeAccess employeeAccess = null;
		String url = getMethodURL();
		String passwdSHA1 = SHA1(passwd);
		LoginRequest req = new LoginRequest(userName, passwdSHA1, c2dmRegistrationId);
		employeeAccess = (EmployeeAccess) postReturn(url, req, EmployeeAccess.class);
		return employeeAccess;
	}
	
	public void ChangePassword(String oldPasswd, String newPasswd) throws NoSuchAlgorithmException, UnsupportedEncodingException, ServiceUnavailableException{
		String oldPasswdSHA1 = SHA1(oldPasswd);
		String newPasswdSHA1 = SHA1(newPasswd);
		String url = getMethodURL();
		ChangePasswordRequest req = new ChangePasswordRequest(oldPasswdSHA1, newPasswdSHA1);
		post(url, req);
	}
	
    private String convToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9))
                    buf.append((char) ('0' + halfbyte));
                else
                        buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        }
        return buf.toString();
    }

    private String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException  {
	    MessageDigest md = MessageDigest.getInstance("SHA-1");
	    byte[] sha1hash = new byte[40];
	    md.update(text.getBytes("iso-8859-1"), 0, text.length());
	    sha1hash = md.digest();
	    return convToHex(sha1hash);
    }
}
